import React, {Component} from 'react';
import styles from './header.less'
import packageConfig from '@@/package'
import { category } from '@/data/data'
import { Modal, Menu, Dropdown, message } from 'antd'
import { NavLink } from 'dva/router'
import { withRouter } from 'dva/router'
import { getToken } from "../../utils/authority"
import { Tabs } from 'antd'
import { login, logout, register } from '@/services/login'
import RegisterForm from '@/components/RegisterForm/RegisterForm'
import LoginForm from '@/components/LoginForm/LoginForm'

const { TabPane } = Tabs


const routerMap = [
  {
    name: '课程列表',
    path: '/course'
  },
  {
    name: '我的课程',
    path: '/myCourse'
  },
  {
    name: '我的订单',
    path: '/order'
  },
  {
    name: '收货地址',
    path: '/address'
  },
  {
    name: '购物车',
    path: '/shoppingCar'
  },
  {
    name: '退出登录',
    action: 'login/logout'
  }
]

class Header extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      btnText: '课程列表'
    }
  }

  handleLogin() {
    this.setState({
      visible: true
    })
  }

  handleCancel() {
    this.callback()
    this.setState({
      visible: false
    })
  }

  menuAction(item) {
    const { history } = this.props
    item.path && this.setState({
      btnText: item.name
    }, () => {
      history.push(item.path)
    })
    item.action && this.logout()
  }

  async logout() {
    let res = await logout()
    if (res.data.code == 0) {
      message.destroy()
      message.success('退出成功')
      localStorage.removeItem('token')
      setTimeout(() => {
        window.location.href = '/'
      }, 300)
    }
  }

  renderMenu = () => {
    const { location: { pathname } } = this.props
    const menu = (
      <Menu className={'login_menu'}>
        {
          routerMap.map((item, index) => {
            const { path } = item
            return (
              <Menu.Item className={path && pathname.includes(item.path) ? 'activeMenu Item': 'Item'} onClick={this.menuAction.bind(this, item)} key={index}>
                <span>{item.name}</span>
              </Menu.Item>
            )
          })
        }
      </Menu>
    )
    return menu
  }

  componentDidMount() {
    this.renderBtnTxt()
  }

  // 刷新初始化按钮文字
  renderBtnTxt() {
    const { location: { pathname } } = this.props
    let name = routerMap.find(item => {
      if (item.path) {
        return pathname.includes(item.path)
      } else {
        return false
      }
    })?.name || '课程列表'
    this.setState({
      btnText: name
    })
  }

  // 表单校验成功
  async onFinish(data) {
    let res = await login({...data})
    if (res.data.code == 0) {
      localStorage.setItem('token', res.data.data.token)
      message.destroy()
      message.success('登录成功')
      this.setState({
        visible: false
      }, () => {
        setTimeout(() => {
          window.location.href = '/'
        }, 300)
      })
    } else {
      message.error(res.data.msg)
    }
  }

  async onFinishRegister(data) {
    let res = await register({...data})
    if (res.data.code == 0) {
      message.destroy()
      message.success('注册成功')
      this.setState({
        visible: false
      })
    } else {
      message.error(res.data.msg)
    }
  }

  callback() {
    this.refs.LoginForm && this.refs.LoginForm.resetForm()
    this.refs.RegisterForm && this.refs.RegisterForm.resetForm()
  }

  render() {
    const { visible, btnText } = this.state
    return (
      <div className={styles.clearFixed}>
        <div className={styles.header}>
          <div className={styles.container}>
            <div className={styles.logo}>{packageConfig.title}</div>
            <ul className={styles.category}>
              {
                category.map((item, index) => {
                  return <NavLink key={index} to={item.path} exact activeClassName={'active'}>{item.title}</NavLink>
                })
              }
            </ul>
            {
              !getToken() ?
                <div className={styles.login} onClick={this.handleLogin.bind(this)}>登录/注册</div> :
                <Dropdown overlay={this.renderMenu()} placement="bottomRight" arrow>
                  <div className={styles.loginBtn}>{btnText}</div>
                </Dropdown>
            }
              <Modal closable={false} width='400px' footer={null} onCancel={this.handleCancel.bind(this)} visible={visible} destroyOnClose>
                <Tabs defaultActiveKey="1" onChange={this.callback.bind(this)}>
                  <TabPane tab="登录" key="1" style={{padding: '0'}}>
                    <LoginForm onFinish={this.onFinish.bind(this)} ref={'LoginForm'}/>
                  </TabPane>
                  <TabPane tab="注册" key="2" style={{padding: '0'}}>
                    <RegisterForm onFinish={this.onFinishRegister.bind(this)} ref={'RegisterForm'}/>
                  </TabPane>
                </Tabs>
              </Modal>
          </div>
        </div>
      </div>
    );
  }
}

export default withRouter(Header);